package Runde4;
import java.util.Scanner;

public class IntTree {
	private ReplaceableTree tree;
	
	/**
	 * @postcondition Creates a new tree with given a root node, labeled with the given param
	 * @param root - IntTree's new root-node
	 * @throws InvalidParamException - if replaceabletree throws exception
	 */
	public IntTree(int root) throws InvalidParamException {
		try {
			tree = new ReplaceableTree(String.valueOf(root));
		} catch (InvalidParamException e) {
			throw e;
		}
	}
	
	/**
	 * @postcondition Returns true / false whether tree contains a node labeled with given int, or not
	 * @param node - node-label to look for
	 * @throws InvalidParamException - if replaceabletree throws exception
	 */
	public boolean contains(int node) throws InvalidParamException {
		try {
		return tree.contains(String.valueOf(node));
		} catch (InvalidParamException e) {
			throw e;
		}
	}
	
	/**
	 * @postcondition Returns path to node with label matching to the given int if found
     * @param node - node-label to look for
	 * @throws InvalidParamException - if replaceabletree throws exception
	 */
	public String search(int node) throws InvalidParamException {
		try {
			return tree.search(String.valueOf(node));
		} catch (InvalidParamException e) {
			throw e;
		}
	}
	
	/**
	 * @postcondition Adds a node with given int as label
	 * @param node - label of the node that should be added
	 */
	public void add(int node) {
		tree.add(String.valueOf(node));
	}
	
	/**
	 * @postcondition Returns a readable output of StringTree
	 */
	public String toString() {
		return tree.toString();
	}
	
	/**
	 * @precondition subTree.length()>0
	 * @postcondition replaces node and children on position with the given subTree
	 * @param position - position which should be replaced
	 * @param subTree - new subTree on given position
	 */
	public void replace(String position, String subTree) {
		Scanner s = new Scanner(subTree).useDelimiter("\n");
		String temp;
		while(s.hasNext()) {
			temp = s.next();
			temp = temp.replace('*', ' ');
			temp = temp.trim();
			try {
				if(temp.length()>0)
					Integer.parseInt(temp);
			} catch (Exception e) {
				System.out.println(e);
				return;
			}
		}
		System.out.println("test");
		tree.replace(position, subTree);
	}
}
